package com.zhanglinwei.openApiClient.utils;

import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.io.Resources;

public class ClassUtils {

    private ClassUtils(){}

    private static ClassLoader systemClassLoader;

    static {
        try {
            systemClassLoader = ClassLoader.getSystemClassLoader();
        } catch (SecurityException ignored) {
            // AccessControlException on Google App Engine
        }
    }

    public static Class<?> toClassConfident(String name, ClassLoader classLoader) {
        try {
            return loadClass(name, getClassLoaders(classLoader));
        } catch (ClassNotFoundException e) {
            throw ExceptionUtils.mpe("找不到指定的class！请仅在明确确定会有 class 的时候，调用该方法", e);
        }
    }

    public static Class<?> loadClass(String classFullPath) {
        Class<?> aClass = null;

        if (StringUtils.isNotBlank(classFullPath)) {
            try {
                aClass = Class.forName(classFullPath);
            } catch (ClassNotFoundException e) {
                // ignore
            }
        }

        return aClass;
    }

    private static Class<?> loadClass(String className, ClassLoader[] classLoaders) throws ClassNotFoundException {
        for (ClassLoader classLoader : classLoaders) {
            if (classLoader != null) {
                try {
                    return Class.forName(className, true, classLoader);
                } catch (ClassNotFoundException e) {
                    // ignore
                }
            }
        }
        throw new ClassNotFoundException("Cannot find class: " + className);
    }

    private static ClassLoader[] getClassLoaders(ClassLoader classLoader) {
        return new ClassLoader[]{
                classLoader,
                Resources.getDefaultClassLoader(),
                Thread.currentThread().getContextClassLoader(),
                com.baomidou.mybatisplus.core.toolkit.ClassUtils.class.getClassLoader(),
                systemClassLoader};
    }
}
